<?php
	
	//print_r($this->puzzle);
	
	$db = $this->puzzle->PDM->default_container;
	
	// Load user from database
	$list = $db->listEntity("user", "php-puzzle-directory", "username = '".$this->params->username."'");
	$u = $list->elements[0];
	
	if ($u->id != "")
	{
		// Calculate the hash of the user
		$seed = $u->id . $u->username . $this->params->password;
		$hash = strtoupper(sha1($seed));
		
		// If the password matches the hash...
		if ($u->username == $this->params->username && $u->password == $hash)
		{
			// Create login token
			$token->user = $u;
			$token->date_start = date("Y-m-d H:i:s");
			$_SESSION['login_token'] = serialize($token);
			
			$login = true;
		}
	}
	
	
	// Generate cookie if must remember
	
	if ($login == true && $this->params->remember == true)
	{
		$seed = $u->id . $u->username . $u->password . $token->date_start;
		$secret = strtoupper(sha1($seed));
		
		$expire = time() + 60*60*24*30;
		
		setcookie("username", $u->username, $expire);
		setcookie("date_start", $token->date_start, $expire);
		setcookie("secret", $secret, $expire);
	}
	else if ($login == false)
	{
		setcookie("username", "", time() - 3600);
		setcookie("date_start", "", time() - 3600);
		setcookie("secret", "", time() - 3600);
	}
	
	// Generate response
	
	$view_return = $this->puzzle->PVM->createView("element", "php-puzzle-xml");
	$view_return->params->name = "return";
	$view_return->params->attributes = array(array('name' => 'result', 'value' => 'ok'));
	$view_return->params->content = "OK";
	
	$view_response = $this->puzzle->PVM->createView("puzzle-response", "php-puzzle-bigbang");
	$view_response->params->elements = array();
	$view_response->params->elements[] = $view_return;
	
	$view_response->initialize();
	$view_response->render();
	
?>
